//
//  GRXStrollVC.m
//  1-MushroomStreet-自定义tabbar
//
//  Created by xmg on 15/12/8.
//  Copyright © 2015年 grx. All rights reserved.
//

#import "GRXStrollVC.h"
#import "UIView+Frame.h"

#import "AttentionTVC.h"
#import "TrendTVC.h"
#import "PrivateTVC.h"
#import "StarListTVC.h"
#import "AppearTVC.h"
#import "FaceSupportTVC.h"
#import "TastyTVC.h"
#import "TravelTVC.h"

#import "GRXCustomMenu.h"
#import "GRXSlideView.h"

#import "GRXStrollHeaderView.h"
#import "GRXSlideView.h"


#import "QRCodeController.h"

@interface GRXStrollVC ()<GRXCustomMenuDelegate,UIScrollViewDelegate>

/**弹框菜单*/
@property (nonatomic, strong) GRXCustomMenu *menu;

/*=========头部视图相关==========*/
/**头部视图*/
@property (nonatomic, weak) GRXStrollHeaderView *headerView;

/**选项卡*/
@property (nonatomic, weak) UIScrollView *alertView;

/**记录当前点击的按钮*/
@property (nonatomic, weak) UIButton *currentButton;

/**底部滚动view*/
@property (nonatomic, weak) UIView *bottomView;
/*=========头部视图相关==========*/


/*=========内容滚动视图相关==========*/
/**内容滚动视图*/
@property (nonatomic, weak) GRXSlideView *contentScrollView;

/**当前添加的tableView*/
@property (nonatomic, weak) UIScrollView *currentTableView;

/**记录切换前当前滚动的tableView最终偏移量*/
@property (nonatomic,assign)CGPoint offset;
/*=========内容滚动视图相关==========*/


/*=========手势相关==========*/
/**触点是否再头部视图上*/
@property (nonatomic,assign,getter=isOnHeaderView)BOOL isOnHeaderView;

/**手指刚落在头部视图上的点*/
@property (nonatomic,assign)CGPoint initPoint;
/**判断手指是否正在下滑*/
@property (nonatomic,assign,getter=isDown)BOOL isDown;

/**选项卡的按钮数组*/
@property (nonatomic,strong)NSMutableArray *titleButtons;

/*=========手势相关==========*/

@end

@implementation GRXStrollVC

/**
 *数据懒加载
 */
- (NSMutableArray *)titleButtons
{
    if (!_titleButtons) {
        _titleButtons = [[NSMutableArray alloc] init];
    }
    return _titleButtons;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //设置背景色
    self.view.backgroundColor = kGRXColor(255, 70, 112);
    //禁止导航条修改tableView的额外滚动区域
    self.automaticallyAdjustsScrollViewInsets = NO;

    //设置导航条
    [self setUpNavigation];
    
    //添加子控制器
    [self addChildController];
    
    //设置头部视图区域
    [self setUpHeaderView];
    
    //设置内容scrollView
    [self addContentScrollView];
    
    //界面一出现就加载第一个子控制器的view
    [self addChildControllerViewToScrollView];
    
    
}



#pragma mark ---设置内容视图
- (void)addContentScrollView{
    GRXSlideView *contentScrollView = [[GRXSlideView alloc] init];
    contentScrollView.frame = CGRectMake(0, 0, self.view.width, self.view.height);
    contentScrollView.backgroundColor = [UIColor clearColor];
    
    //传入headerView,返回最合适的区域
    [contentScrollView deliverHeaderView:self.headerView];
    
    self.isOnHeaderView = NO;
    contentScrollView.showsHorizontalScrollIndicator = NO;
    contentScrollView.pagingEnabled = YES;
    contentScrollView.bounces = NO;
    
    
    //设置代理
    contentScrollView.delegate = self;
    
    //根据子控制器的个数确定内容尺寸
    NSInteger count = self.childViewControllers.count;
    
    contentScrollView.contentSize = CGSizeMake(kScreenW * count, 0);
    self.contentScrollView = contentScrollView;
    [self.view addSubview:contentScrollView];
    
    
    //接收tableView发送的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewDidScroll:) name:GRXChangeChildViewControllerNotification object:nil];
}

- (void)tableViewDidScroll:(NSNotification *)notification{
    //通过userInfo字典取出发送通知的tableView,获取该tableView的偏移量
    UIScrollView *tempScrollView = notification.userInfo[@"scrollView"];
    
    //通过通知监听子控制器的tableView的滚动
    if (!self.isOnHeaderView) {
    
        if (tempScrollView.contentOffset.y  <= -GRXAlternativeHeight-GRXNavgationBarMaxY) {
            
            self.headerView.y = -(self.headerView.height + tempScrollView.contentOffset.y);
            [self.view bringSubviewToFront:self.contentScrollView];
            
        }else {
            
             self.headerView.y = -(self.headerView.height - GRXNavgationBarMaxY - GRXAlternativeHeight);
            [self.view bringSubviewToFront:self.headerView];
            
        }
        
    }
}



#pragma mark ---UIScrollViewDelegate代理
/**
 * scrollView滚动完毕\静止的时候调用这个代理方法
 * 前提:用户拖拽scrollView, 手松开以后继续滚动
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    //获取对应的按钮
    NSInteger index = scrollView.contentOffset.x / scrollView.width;
    
    //选中按钮
//    [self selectTitleButton:self.titleButtons[index]];
    UIButton *titleButton = self.titleButtons[index];
    
    [self alertButtonClick:titleButton];
    

}


#pragma mark ---设置头部视图
- (void)setUpHeaderView{
    //添加头部整体View
    GRXStrollHeaderView *headerView = [[GRXStrollHeaderView alloc] init];
    headerView.frame = CGRectMake(0, GRXNavgationBarMaxY, kScreenW, GRXStrollHeaderViewHeight);
    headerView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:headerView];
    self.headerView = headerView;
    
    
    
    //添加手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
    [headerView addGestureRecognizer:pan];
    
    //添加选项卡
    [self setUpAlertView];
}


#pragma mark ---头部视图手势
- (void)panGestureRecognizer:(UIPanGestureRecognizer *)pan{
    
    //获取当前手指在headerView上的点坐标
    CGPoint position = [pan locationInView:self.headerView];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        
        self.isOnHeaderView = YES;
        
        self.initPoint = [pan locationInView:self.headerView];
        
    }else if (pan.state == UIGestureRecognizerStateChanged){
       
        CGFloat dela = position.y - self.initPoint.y;//手指在头部视图移动的距离
            self.headerView.y += dela;
        
        //如果当前滚动的tableView的偏移量大于或者等于了负的导航条和选项卡的高度的话,那么就让headerView悬停在顶部
        if (self.currentTableView.contentOffset.y >= - GRXAlternativeHeight-GRXNavgationBarMaxY) {
            self.headerView.y = - (self.headerView.height - GRXAlternativeHeight-GRXNavgationBarMaxY);
            [self.view bringSubviewToFront:self.headerView];
        }
        
        
        
        //修改当前滚动的tableView的偏移量(headerView滚动了多少距离,就让tableView偏移量减少多少)
        CGPoint offset = self.currentTableView.contentOffset;
        offset.y -= position.y - self.initPoint.y;
        self.currentTableView.contentOffset = offset;
    
        //复位操作
        offset = CGPointZero;
        
       

    }else if (pan.state == UIGestureRecognizerStateEnded){
       
        self.isOnHeaderView = NO;
        
        if (self.currentTableView.contentOffset.y <= -GRXNavgationBarMaxY-self.headerView.height) {
            //如果是下拉,就让tableView反弹或原位置
            [UIView animateWithDuration:0.1 animations:^{
                self.currentTableView.contentOffset = CGPointMake(0, -self.headerView.height - GRXNavgationBarMaxY);
            }];
        }
    }
}





#pragma mark ---选项卡初始化
//设置选项卡
- (void)setUpAlertView{
    //添加导航条
    UIScrollView *alertView = [[UIScrollView alloc] init];
    alertView.frame = CGRectMake(0, self.headerView.height - GRXAlternativeHeight, self.headerView.width, GRXAlternativeHeight);
    alertView.showsHorizontalScrollIndicator = NO;
    
    alertView.layer.borderWidth = 0.5;
    alertView.layer.borderColor = kGRXColor(200, 200, 200).CGColor;
    
    alertView.bounces = NO;
    //内容尺寸在添加按钮之后确定
    alertView.backgroundColor = kGRXColor(245, 245, 245);
    [self.headerView addSubview:alertView];
    self.alertView = alertView;
   
    //给选项卡添加按钮
    [self addAlertButton];
    
    //添加底部滚动视图
    [self addBottomView];
}


//给选项卡添加按钮
- (void)addAlertButton{
    
    NSArray *alertTitles = @[@"关注",@"热门",@"私搭",@"星榜",@"晒货",@"脸赞",@"好吃",@"旅行"];
    CGFloat w = 60;//确定按钮的宽度
    CGFloat h = self.alertView.height;
    CGFloat x = 0;
    CGFloat y = 0;
    
    for (int i = 0; i < alertTitles.count; i++) {
        UIButton *alertButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [alertButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [alertButton setTitleColor:kGRXColor(255, 70, 112) forState:UIControlStateSelected];
        [alertButton setTitle:alertTitles[i] forState:UIControlStateNormal];
        alertButton.titleLabel.font = [UIFont systemFontOfSize:15];
        x = i * w;
        alertButton.tag = i;
        alertButton.frame = CGRectMake(x, y, w, h);
        
        //监听按钮点击
        [alertButton addTarget:self action:@selector(alertButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.alertView addSubview:alertButton];
        
        //把按钮保存到数组中
        [self.titleButtons addObject:alertButton];
        
        
        UIView *separatedLine = [[UIView alloc] init];
        separatedLine.frame = CGRectMake((w - 1) * i, y + 16, 1, 15);
        separatedLine.backgroundColor = kGRXColor(200, 200, 200);
        [self.alertView addSubview:separatedLine];
    }
    
    //根据标题的个数确定选项卡内容尺寸
    self.alertView.contentSize = CGSizeMake(w * alertTitles.count, 0);
}

//添加底部滚动View
- (void)addBottomView{
    //取出第一个按钮
    UIButton *firstTitleButton = self.alertView.subviews.firstObject;
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = kGRXColor(255, 70, 112);
    bottomView.height = 2;
    bottomView.y = self.alertView.height - bottomView.height;
    [self.alertView addSubview:bottomView];
    
    self.bottomView = bottomView;
    
    firstTitleButton.selected = YES;
    self.currentButton = firstTitleButton;
    
    //这是为了一进入程序,底部滚动条就能拿到第一个按钮的label的宽度
    [firstTitleButton.titleLabel sizeToFit];// 通过这句代码计算按钮内部label的宽度
    
    //让底部滚动条的宽度跟随标题的宽度改变
    bottomView.width = firstTitleButton.titleLabel.width;//想要给宽度两边各加一点距离,只要加上总的距离就会在两边各多出一段距离
    
    //初始化底部滚动条,使界面一出现就显示在第一个按钮下面
    bottomView.centerX = firstTitleButton.centerX;
}


//选项卡按钮点击事件
- (void)alertButtonClick:(UIButton *)btn{
    //选中按钮
    [self selectTitleButton:btn];
    
    
    
    [UIView animateWithDuration:0.25 animations:^{
        self.bottomView.width = btn.titleLabel.width;
        self.bottomView.centerX = btn.centerX;
        
        //让对应的view滚动到可见范围内
        CGPoint offset = self.contentScrollView.contentOffset;
        offset.x = btn.tag * self.contentScrollView.width;
        self.contentScrollView.contentOffset = offset;

    } completion:^(BOOL finished) {
        
        // 记录当前tableView的最后一次偏移量的y值
        self.offset = self.currentTableView.contentOffset;
        
        //把下一个tableView添加到内容滚动视图中
        [self addChildControllerViewToScrollView];
    }];
    
}

// 选中按钮,点击和滚动完成都会调用
- (void)selectTitleButton:(UIButton *)alertButton{
    
    self.currentButton.selected = NO;
    alertButton.selected = YES;
    self.currentButton = alertButton;
    
    //设置选中按钮滚动到中间
    [self setUpTitleButtonCenter:alertButton];
}

//设置标题选中居中
- (void)setUpTitleButtonCenter:(UIButton *)btn{
    
    //计算偏移量 == 选中按钮的中心点x - screen * 0.5
    CGFloat offectX = btn.center.x - kScreenW * 0.5;
    
    if (offectX < 0) {
        offectX = 0;
    }
    
    //计算最大滚动区域
    CGFloat maxOffectX = _alertView.contentSize.width - kScreenW;
    
    if (offectX > maxOffectX) {
        offectX = maxOffectX;
    }
    
    //移动
    [_alertView setContentOffset:CGPointMake(offectX, 0) animated:YES];
}


#pragma mark ---添加子控制器
- (void)addChildController{
    
    [self addChildViewController:[[AttentionTVC alloc] init]];
    [self addChildViewController:[[TrendTVC alloc] init]];
    [self addChildViewController:[[PrivateTVC alloc] init]];
    [self addChildViewController:[[StarListTVC alloc] init]];
    [self addChildViewController:[[AppearTVC alloc] init]];
    [self addChildViewController:[[FaceSupportTVC alloc] init]];
    [self addChildViewController:[[TastyTVC alloc] init]];
    [self addChildViewController:[[TravelTVC alloc] init]];
}

//添加子控制器的视图到内容滚动视图中
- (void)addChildControllerViewToScrollView{
    
    //取出对应的子控制器
    NSInteger index = self.contentScrollView.contentOffset.x / self.contentScrollView.width;
    UITableViewController *controller = self.childViewControllers[index];

//    controller.tableView.delegate = self;
    //如果当前控制器的view已经添加,就直接返回
    if (controller.view.superview) {
        self.currentTableView = controller.tableView;
        return;
    };
    
    controller.view.frame = self.contentScrollView.bounds;
    
    controller.tableView.contentInset = UIEdgeInsetsMake(GRXNavgationBarMaxY + GRXStrollHeaderViewHeight, 0, 49, 0);
    
    //判断当前的tableView是否存在,以确定第一个tableView的位置
    if (self.currentTableView != nil) {
        
        //判断选项卡是否滚动到顶部
        if (self.offset.y > -GRXAlternativeHeight) {
            
            //如果滚动到顶部,就让所有的tableView的内容偏移量的y值向下滚动导航条和选项卡的高度之和
            self.offset = CGPointMake(0, -GRXNavgationBarMaxY-GRXAlternativeHeight);
        }

        controller.tableView.contentOffset = self.offset;
    }
    
    [self.contentScrollView addSubview:controller.view];
    
    //把当前显示的tableView记录下来
    self.currentTableView = ((UITableViewController *)self.childViewControllers[index]).tableView;
}

#pragma mark ---设置导航条
- (void)setUpNavigation{
    UIBarButtonItem *rightItem = [UIBarButtonItem itemWithNorImage:[UIImage imageNamed:@"dd_contacts_right_bar"] highImage:[UIImage imageNamed:@"dd_contacts_right_bar"] target:self action:@selector(addClick)];
    
    self.navigationItem.rightBarButtonItem = rightItem;
    
    //导航条的搜索按钮(暂未监听点击)
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 200, 30);
    [btn setImage:[UIImage imageNamed:@"index_search_brand"] forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor grayColor];
    self.navigationItem.titleView = btn;
}

//导航条右边按钮点击事件
- (void)addClick{
    __weak __typeof(self) weakSelf = self;
    if (!self.menu) {
        
        self.menu = [[GRXCustomMenu alloc] initWithDataArr:@[@"查找好友", @"扫一扫"] origin:CGPointMake(0, GRXNavgationBarMaxY) width:120 rowHeight:44];
        
        //        self.menu.backgroundColor = [UIColor blueColor];
        //        NSLog(@"%@",NSStringFromCGRect(self.menu.frame));
        _menu.delegate = self;
        _menu.dismiss = ^() {
            weakSelf.menu = nil;
        };
        _menu.arrImgName = @[@"dd_add_friend",@"schoolListItem"];
        [self.view addSubview:_menu];
    } else {
        [_menu dismissWithCompletion:^(GRXCustomMenu *object) {
            weakSelf.menu = nil;
        }];
    }
}

//界面消失的时候,弹窗也跟着消失
- (void)viewDidDisappear:(BOOL)animated{
    __weak __typeof(self) weakSelf = self;
    [super viewDidDisappear:animated];
    
    [_menu dismissWithCompletion:^(GRXCustomMenu *object) {
        weakSelf.menu = nil;
    }];
}

#pragma mark ---GRXCustomMenuDelegate(弹窗代理)
- (void)customMenu:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1) {
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"QRCodeController" bundle:nil];
        
        QRCodeController *qrcodeController = storyboard.instantiateInitialViewController;
        [self presentViewController:qrcodeController animated:YES completion:nil];
    }
}


#pragma mark ---网络数据加载
- (void)loadNewData{
    
    
}

#pragma mark ---销毁通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
